using System;
using System.IO;
using GameFramework.GameObjects;

namespace GameFramework.Diagnostics
{
    /// <summary>
    /// This game object show benchmark information on the screen.
    /// </summary>
    public class FrameRateLabel : Label
    {
        /// <summary>
        /// The number of draw calls from the last benchmark update.
        /// </summary>
        private int drawCount;

        /// <summary>
        /// The number of update calls from the last benchmark update.
        /// </summary>
        private int updateCount;

        /// <summary>
        /// The timespan of the last benchmark update.
        /// </summary>
        private TimeSpan lastBenchmarkUpdate;

        /// <summary>
        /// Initializes a new instance of the <see cref="FrameRateLabel"/> class.
        /// </summary>
        public FrameRateLabel()
        {
            Initialize();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="FrameRateLabel"/> class.
        /// </summary>
        /// <param name="fontName">The font Name.</param>
        public FrameRateLabel(string fontName) : this()
        {
            FontName = fontName;
        }

        /// <summary>
        /// Update the object.
        /// </summary>
        public override void Update()
        {
            base.Update();

            if (GameTime.TotalGameTime > lastBenchmarkUpdate + TimeSpan.FromSeconds(1))
            {
                Text = String.Format("Draw per second: {0}\nUpdate per second: {1}", drawCount, updateCount);

                drawCount = 0;
                updateCount = 0;
                lastBenchmarkUpdate = GameTime.TotalGameTime;
            }

            updateCount++;
        }

        /// <summary>
        /// Draw the object.
        /// </summary>
        public override void Draw()
        {
            base.Draw();

            drawCount++;
        }

        /// <summary>
        /// Read the status of the object from the binary stream.
        /// </summary>
        /// <param name="reader">The binary reader.</param>
        public override void Read(BinaryReader reader)
        {
            base.Read(reader);

            Initialize();
        }

        /// <summary>
        /// Initialize the object.
        /// </summary>
        private void Initialize()
        {
            drawCount = 0;
            updateCount = 0;
            lastBenchmarkUpdate = TimeSpan.Zero;
            Position = ScreenCenter;
        }
    }
}